const Users = require('../db/index').Users

const createToken = require('../utils/createToken.js') // 创建token
const checkToken = require('../utils/checkToken.js') // 验证token
const { uniqueObjArr } = require('../utils/index.js')


const loginIn = async (ctx) => {
    const { username, password } = ctx.request.body
    let doc = await Users.findOne({username:username}).populate({
      path: 'roles',
      select: '-_id',
      populate: { 
        path: 'routerResources permissionResources',
        select: '-_id',
      }
    })
    const userRoles = doc.roles
    const userRouters = uniqueObjArr(userRoles.reduce((pre,next)=>{
      return next.routerResources?next.routerResources:[]
    },[]))
    const userPermissions = uniqueObjArr(userRoles.reduce((pre,next)=>{
      return next.permissionResources?next.permissionResources:[]
    },[]))
    
    if (!doc) {
        ctx.body = {
            code: -1,
            msg: '用户名不存在'
        }
    } else if (doc.password !== password) {
        ctx.body = {
            code: -1,
            msg: '密码错误'
        }
    } else if (doc.password === password) {
        let token = createToken(doc._id) // 生成token 
        // doc.token = token
        try {
            // await doc.save() // 更新mongo中对应用户名的token
            ctx.body = {
                code: 200,
                msg: '登录成功',
                userInfo:{
                  id:doc._id,
                  username,
                  token
                },
                userRouters:userRouters,
                userPermissions:userPermissions
            }
        } catch (err) {
            ctx.body = {
                code: -1,
                msg: '登录失败，请重新登录'
            }
        }
    }
}

const logout = (ctx) => {
  ctx.body = {
    code: 200,
    msg: '退出成功',
  }
}
const authFunc = {
    loginIn,
    logout
};
module.exports = authFunc